package com.nulldev.util.web.HttpServer3.extensions.http2.api_compat;

import java.io.InputStream;
import java.util.Map;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.Variables;
import com.nulldev.util.web.HttpServer3.HttpServer;
import com.nulldev.util.web.HttpServer3.Page;
import com.nulldev.util.web.HttpServer3.ReadRequest;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.extensions.http2.compat.HttpBodyStream;
import com.nulldev.util.web.HttpServer3.extensions.http2.compat.HttpRequest;
import com.nulldev.util.web.HttpServer3.extensions.http2.compat.ResponseBuilder;
import com.nulldev.util.web.HttpServer3.legacyPages.v1.RequestType;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3.Request;
import com.nulldev.util.web.HttpServer3.pages.v3.RequestProtocolType;
import com.nulldev.util.web.URLUtils.nStreamHandlerFactory;

public class HttpRequestDispatcher {

	final HttpServer server;

	public HttpRequestDispatcher(final HttpServer httpServer) {
		this.server = Variables.requireNonNullObject(httpServer, "httpServer");
	}

	public ResponseBuilder dispatchObjectToHandlers(final HttpRequest request) {
		final InputStream is = nStreamHandlerFactory.BLANK;
		final Request r = new Request(request.getBasicInfo().getPath().get(), is, "0.0.0.0", RequestProtocolType.HTTP_2_0, request.getSocket().getSocket());
		final String id = request.getBasicInfo().getPath().get();
		final Page p = this.server.getPage(id, request.getSocket().getSocket());
		final Map<String, String> headers = r.getHeaders();
		if (p == null) {
			final ResponseBuilder response = ResponseBuilder.getInstance(400, new HttpBodyStream());
			return response;
		} else {
			final RequestType type = RequestType.GET; // TODO
			try {
				final ReadRequest rr = new ReadRequest(headers);
				final String[] convertedReq =
					{ request.getBasicInfo().getMethod(), request.getBasicInfo().getPath().get(), request.getBasicInfo().getMethod() };
				final Response resp = Page.do_response(type, convertedReq, rr, this.server, request.getSocket().getSocket(), headers, p);
				final ResponseBuilder response = ResponseBuilder.getInstance(503, new HttpBodyStream());
				response.setResponseCode(resp.getResponseCode());
				response.getHeaders().getHeaders().putAll(resp.getCustomHeaders());
				if (resp.hasCustomMime()) {
					response.getHeaders().add("content-type", resp.getCustomMime());
				}
				if (resp.copyable()) {

				} else if (resp.nioCopyable()) {

				} else {
					response.getHeaders().add("content-length", String.valueOf(resp.getInputStream().available()));
					response.setBody(new HttpBodyOutputStream(resp.getInputStream()));
				}
				return response;
			} catch (Exception e) {
				JVM.errorln(e);
				final ResponseBuilder response = ResponseBuilder.getInstance(503, new HttpBodyStream());
				return response;
			}
		}
	}

}
